package com.zoke.support.image.activity;

import java.io.File;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;

import com.zoke.support.R;
import com.zoke.support.base.BaseActivity;
import com.zoke.support.image.activity.GalleryActivity.PhotoRequestCode;
import com.zoke.support.utils.FileUtil;
import com.zoke.support.utils.LogUtil;
import com.zoke.support.view.ZokeToast;
import com.zoke.support.view.lib.cropper.CropImageView;

/**
 * 裁切图片 需要支持照相机跳转调用Imagecut裁切图片
 * 
 * @author JackWu
 * @version
 * @date 2014-11-19
 * @_QQ_ 651319154
 */
public class ImageCutActivity extends BaseActivity {
	/** 被裁剪图片的地址 **/
	public static final String CUTIMAGEPATH = "_image_path";
	private String mCutPath;
	private CropImageView mCroperImage;
	/** 旋转角度 **/
	private static final int ROTATE_NINETY_DEGREES = 90;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_imagecut);
		mTitleManager.setTitleIcon(R.drawable.imagecut_rotate).setRightText("裁剪").setLeftText("取消")
				.setBackgroundResource(R.drawable.imagecut_bg);
		mCutPath = getIntent().getStringExtra(CUTIMAGEPATH);
		mCroperImage = (CropImageView) findViewById(R.id._cropimage_iv);
		mCroperImage.setFixedAspectRatio(true);
		// 最好是固定死了 -- 是屏幕宽度的多少
		mCroperImage.setAspectRatio(30, 30);
		mCroperImage.setGuidelines(1);// 0 1 2
		if (TextUtils.isEmpty(mCutPath)) {
			return;
		}
		BitmapFactory.Options options = new BitmapFactory.Options();
		Bitmap b = BitmapFactory.decodeFile(mCutPath, options);
		mCroperImage.setImageBitmap(b);
	}

	@Override
	public void onTitleClickRight(View view) {
		super.onTitleClickRight(view);
		Bitmap cropBit = mCroperImage.getCroppedImage();
		// 存储为文件并回传
		String filetarget = FileUtil.getSDPath()+File.separator+".swgl"+File.separator+".image"+File.separator;
		String filePath = FileUtil.BitmapToFile(cropBit, filetarget);
		LogUtil.e("---存储路径=="+filePath);
		if(TextUtils.isEmpty(filePath)){
			ZokeToast.show(getApplicationContext(), "裁剪失败，内存卡异常");
			return;
		}
		Intent data = new Intent();
		data.putExtra(PhotoRequestCode.REQUESTKEY, filePath);
		setResult(PhotoRequestCode.CROP, data);
		ImageCutActivity.this.onBackPressed();
	}

	@Override
	public void onTitleClick(View view) {
		super.onTitleClick(view);
		mCroperImage.rotateImage(ROTATE_NINETY_DEGREES);
	}
}
